//
//  giftMessageDataBase.m
//  tcpoctest
//
//  Created by gump on 6/4/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "giftMessageDataBase.h"

#import "GiftMessageDataSource.h"

#import "giftMessageInfo.h"

@implementation giftMessageDataBase

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists giftmessage(giftid text,\
sendermail text,giftcount int,mail text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM giftmessage where mail = '%@'"
                        ,[DataControl shareControl].personDS.uinfo.mail];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].giftMessageDS  delAllMessage];
    
    while ([s next]) {
        giftMessageInfo *gminfo = [[giftMessageInfo alloc] init];
        
        gminfo.strgiftid = [s stringForColumn:@"giftid"];
        gminfo.strsendermail = [s stringForColumn:@"sendermail"];
        gminfo.igiftcount = [s intForColumn:@"giftcount"];
        
        [[DataControl shareControl].giftMessageDS AddGiftMessage:gminfo];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertGiftMeg:(giftMessageInfo *)gminfo
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    
        NSString *strsql = [NSString stringWithFormat:@"insert into giftmessage \
(giftid,sendermail,giftcount,mail) \
values('%@','%@',%d,'%@')"
                  ,gminfo.strgiftid
                  ,gminfo.strsendermail
                  ,gminfo.igiftcount
                ,[DataControl shareControl].personDS.uinfo.mail];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
